
#### genesybol 转化  ####

# chooseCRANmirror()
# 16
# chooseBioCmirror()
# 5

# BiocManager::install("GEOquery")
# BiocManager::install("hgu133plus2.db")

try({
  setwd('父级路径')
})

try({
  setwd('./genesymbol转换/')
})

library(GEOquery)
library(tidyverse)
library(stringr)
library(hgu133plus2.db)
library(biomaRt)

tcga=read.table("GSE16011_series_matrix.txt",sep="\t",header=T,check.names=F, row.names = 1)
exp <- as.data.frame(tcga)
GPL13497 <- getGEO("GPL8542", destdir=".")##根据用户自己的需求填入GPL号
GPL13497@dataTable@table <- GPL13497@dataTable@table[-1:-11,]
GPL13497@dataTable@table <- GPL13497@dataTable@table[-34172:-34173,]
anno=GPL13497@dataTable@table[,c(1,2)]##不同的号内容不一样，这里需要有个教程

tempdatable <-GPL13497@dataTable@table

ensembl <- useMart("ensembl", dataset = "hsapiens_gene_ensembl")##科学上网
gene_ids <- anno[, 2]  # 提取第二列的 Entrez GeneID
gene_info <- getBM(attributes = c("entrezgene_id", "hgnc_symbol"),
                   filters = "entrezgene_id",
                   values = gene_ids,
                   mart = ensembl)
anno <- merge(anno, gene_info, by.x = "ORF", by.y = "entrezgene_id", all.x = TRUE)

dup_rows <- anno[duplicated(anno[, 2]), 2]
dup_suffix <- ave(dup_rows, dup_rows, FUN = seq_along)
anno[duplicated(anno[, 2]), 2] <- paste0(dup_rows, ".", dup_suffix)

# 设置行名为处理后的基因ID
rownames(anno) <- anno[,2]

# 找到 exp 和 anno 中共有的行
com <- intersect(rownames(anno), rownames(exp))

# 根据共有的行过滤 exp 和 anno
exp <- exp[com, ]
anno <- anno[com, ]

# 将 exp 的行名设置为 hgnc_symbol
# 去除 anno 中 hgnc_symbol 的重复值
anno <- anno[!duplicated(anno$hgnc_symbol), ]
anno <- anno[!is.na(anno$hgnc_symbol), ]
# 根据去重后的 anno 更新 exp 的行名
exp <- exp[rownames(anno), ]
rownames(exp) <- anno$hgnc_symbol
write.table(exp,file="GSE16011.txt",sep="\t",quote=F,col.names=T)
